<?php
/**
 * Description of Authenticate
 *
 * @author Ron
 */
class Authenticate {
   private $encodeKey='_ksjd&^GJH';
   private $table='';
   private $idField='';
   private $usernameField='';
   private $passwordField='';
   private $permissionField='';
   public  function __construct(){
       
   }
   public function login($username,$pwd){
       if(strlen($username)>0&&strlen($pwd)>0){
           if($result = $this->checkUser($username,$pwd)){
               $this->setCookiesInfo($result);
               return TRUE;
           }  else {
               return array('error'=>'用户名或密码错误');
           }
       }  else {
           return array('error'=>'用户名或密码为空');
       }
   }
   function checkUser($username,$pwd){
       
   }
   public function isLogined(){
       if(!$this->checkToken()){
           $this->redirect('login.php');
       }else{
           return TRUE;
       }
   }
   public function checkPermission($allow_pid){
       if($this->isLogined()){
           if($this->getPermission()<$allow_pid){
                die('您无权访问该页');
           }
       }
       
   }
   /**
    * 
    * @return int 返回用户权限pid，如果token不匹配则返回-1
    */
   public function getPermission(){
       if($this->checkToken()){
           return $_COOKIE['pid'];
       }else{
           return -1;
       }
   }
   public function checkToken(){
       if(isset($_COOKIE['token'])){
           return $_COOKIE['token']==$this->getToken($_COOKIE['username'],$_COOKIE['uid'],$_COOKIE['pid']);
       }
       return FALSE;
   }
   /**
    * 
    * @param string $str
    * @return string 经过转义的字符串
    */
   function clear($str){
       return addslashes(trim($str)); 
   }
   /**
    * 设置用户信息到Cookies
    * @param array $data 要储存的数据源
    * @param float $time cookies 过期时间，以小时为单位
    * 
    */
   function setCookiesInfo(array $data,$time=1){
       $time = $time*3600;
       setcookie('username',$data[$this->usernameField],time()+$time);
       setcookie('uid',$data[$this->idField],time()+$time);
       setcookie('pid',$data[$this->permissionField],time()+$time);
       $token = $this->getToken($data[$this->usernameField],$data[$this->idField],$data[$this->permissionField]);
       setcookie('token',$token,time()+$time);
   }
   /**
    * 获取验证令牌
    * @param string $username
    * @param string $uid
    * @param string $pid
    * @return string
    */
   function getToken($username,$uid,$pid){

       return md5($username.$uid.$pid.($this->encodeKey).$_SERVER['REMOTE__ADDR']);
   }
   function putSessionInfo($data,$time){
       
   }
   function redirect($url){
       
   }
}

